/**
 * 
 */
package org.atmaca.ert.service;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.atmaca.ert.dao.DbDaoImpl;
import org.atmaca.ert.model.Feed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

/**
 * @author "huseyin_atmaca"
 * 
 */
@Service
@Transactional
public class UpdateRssServiceImpl {

	@Autowired
	private DbDaoImpl dbDao;

	private final Log logger = LogFactory
			.getLog(BatchOperationServiceImpl.class);

	public void updateLink(String link) throws IOException,
			IllegalArgumentException, FeedException {
		Feed feed;

		URL url = new URL(link);
		XmlReader xml = new XmlReader(url);

		SyndFeedInput input = new SyndFeedInput();

		SyndFeed build = input.build(xml);
		List<SyndEntryImpl> entries = build.getEntries();
		for (SyndEntryImpl entry : entries) {
			feed = new Feed();

			feed.setUri(entry.getUri());
			if (!dbDao.isItemExists(feed)) {

				feed.setTitle(entry.getTitle());
				feed.setDescription(entry.getDescription().getValue());
				feed.setFeedUrl(entry.getLink());
				feed.setPublishDate(new Date());

				dbDao.saveItem(feed);
				logger.debug(feed);
			} else {
				break;
			}
		}
	}

}
